package cn.wolfcode.car.interceptor;

import cn.wolfcode.car.ann.RequiredPermission;
import cn.wolfcode.car.context.UserContext;
import cn.wolfcode.car.domain.Permission;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import result.JsonResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取用户请求
        /**
         * 如果拦截的不是controller的方法,直接放行
         */
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod method = (HandlerMethod) handler;
        //2.查看用户请求方法上是否有requiredPermission 注解
        RequiredPermission permissionAnn = method.getMethodAnnotation(RequiredPermission.class);
        //3.无注解 放行
        if (permissionAnn == null) {
            return true;
        }
        //4.有注解 查询用户权限
        UserContext userContext = (UserContext) request.getSession().getAttribute("userContext");
//        if (userContext.getEmployee().isAdmin()) {
//            //超管放行
//            return true;
//        }
        String expression = permissionAnn.expression();
        List<Permission> permissions = userContext.getPermissions();
        //5.判断用户是否有权限,有=>放行,无=>拦截
        for (Permission permission : permissions) {
            //有权限放行
            if (permission.getExpression().equals(expression)) {
                return true;
            }
        }
        //无权限拦截
        //request.getRequestDispatcher("/WEB-INF/views/common/nopermission.ftl");
        ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class);
        if (responseBody == null) {
            //同步
            response.sendRedirect("/error/noPermission");
        } else {
            //异步
            JsonResult jsonResult = JsonResult.error("权限不足");
            String str = JSON.toJSONString(jsonResult);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(str);
        }

        return false;
    }
}
